package com.zf.yichat.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zf.yichat.config.utils.RedisUtil;
import com.zf.yichat.dto.response.ImportRegisterDto;
import com.zf.yichat.mapper.RegisterAutoMapper;
import com.zf.yichat.model.User;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.GroupService;
import com.zf.yichat.service.SysUserService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.service.common.shiro.helper.AdminPasswordHelper;
import com.zf.yichat.utils.common.OKHttpUtil;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ListUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

@Controller
@Slf4j
@RequestMapping("register")
public class RegisterController  extends BaseController {


    @Autowired
    private UserService userService;
    @Autowired
    private BalanceService balanceService;

    @Resource
    private RegisterAutoMapper registerAutoMapper;


    @Value("${st.im_uri}")
    private String imUri;

    /**
     * 导入Excel信息
     */
    @RequestMapping(value = "/importExcel",method = RequestMethod.POST)
    public FsResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception{
        if (file.isEmpty ()) {
            // 处理文件为空的情况
            return FsResponseGen.failMsg ("上传的文件为空");
        }

        try {
            // 将 MultipartFile 转换为 InputStream
            InputStream inputStream = file.getInputStream ();

            // 定义一个数据列表，用于存储读取的数据
            List<ImportRegisterDto> dataList = new ArrayList<>();

            ClassPathResource classPathResource = new ClassPathResource("nickname.json");
            StringBuilder sb = new StringBuilder();
            try {
                InputStream is = classPathResource.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String data;
                while ((data = br.readLine()) != null) {
                    sb.append(data);
                }
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


            JSONArray jsonArray;
            if (sb.length() > 0) {
                jsonArray = JSON.parseArray(sb.toString());
            } else {
                return FsResponseGen.failMsg("获取昵称失败");
            }

            Integer totalCount = registerAutoMapper.sumTotalCount();
            if (totalCount == null) {
                totalCount = 0;
            }
            int startIndex = totalCount + 1;

            StringBuilder resultMsg = new StringBuilder();
            List<Long> ids = new ArrayList<>();

            // 使用 EasyExcel 进行 Excel 文件读取
            EasyExcel.read (inputStream, ImportRegisterDto.class, new AnalysisEventListener<ImportRegisterDto>() {
                @Override
                public void invoke (ImportRegisterDto data, AnalysisContext context) {
                    // 每次读取一行数据时会调用这个方法
                    dataList.add (data); // 读取的数据添加到列表中
                }

                @Override
                public void doAfterAllAnalysed (AnalysisContext context) {
                    int index = 0;
                    // 读取完成后的操作，可以在这里处理 dataList 中的数据
                    for (ImportRegisterDto item : dataList) {
                        // 处理数据
                        index += 1;
                        String mobile = item.getMobile();
                        Integer count = userService.queryUserByMobile(mobile);
                        if (count > 0) {
                            continue;
                        }
                        int currentIndex = (startIndex + index) % 2000;
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("nickname", jsonArray.getString(currentIndex));
                        jsonObject.put("phone", mobile);
                        jsonObject.put("platform", "1");
                        jsonObject.put("region", "86");
                        jsonObject.put("password", "123456");
                        jsonObject.put("deviceId", mobile);
                        jsonObject.put("clientIp", "127.0.0.1");
                        jsonObject.put("recommendCode","235b2g4824dxs");
                        jsonObject.put("verification_token", "239tNGUIJA@&#(nkgj93HFKUW9jfewtewnbu83w98FNSNUEIFCGDSOWEOEIW23N,|GFNDSLOJG");
                        String result = OKHttpUtil.httpPostJson(imUri + "user/register", jsonObject.toJSONString());
                        if (Objects.isNull(result)) {
                            resultMsg.append(mobile).append("、");
                        } else {
                            try {
                                JSONObject resJson = JSONObject.parseObject(result);
                                if (resJson.getInteger("code") != 200) {
                                    resultMsg.append(mobile).append("、");
                                } else {
                                    //设置实名认证和支付密码
                                    try {
                                        User user = userService.selectByMobile(mobile);
                                        ids.add(user.getId());
                                        user.setRealStatus(1);
                                        user.setRealName(String.valueOf(user.getId()));
                                        user.setIdNumber(String.valueOf(user.getId()));
                                        // 使用MD5加密密码
                                        //  user.setPassword(MD5Util.string2MD5(user.getPassword()));
                                        userService.update(user);
                                        //  更新支付密码
                                        balanceService.updatePassword(user.getId(), "123456");

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        resultMsg.append(mobile).append("实名失败、");
                                    }
                                }
                            } catch (Exception e) {
                                resultMsg.append(mobile).append("、");
                            }
                        }
                    }
                }
            }).sheet ().doRead ();

            return FsResponseGen.successData (dataList); // 返回读取的数据或其他处理结果
        } catch (IOException e) {
            e.printStackTrace ();
            return FsResponseGen.failMsg ("文件读取失败");
        }

    }

    // 批量注册
    private void batchRegistration(String mobile){



    }

}
